package cn.iocoder.yudao.module.product.category.service;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.thirdparty.zxhx.ZXHXApiClientFactory;
import cn.iocoder.yudao.framework.thirdparty.zxhx.dto.ZXHXCategoryItemRespDTO;
import cn.iocoder.yudao.module.product.category.dal.dataobject.ProductCategoryDO;
import cn.iocoder.yudao.module.product.category.dal.mysql.ProductCategoryMapper;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.module.api.shop.ConfigConstants.SELF_OPERATED_SHOP_ID;
import static cn.iocoder.yudao.module.api.supply.ConfigConstants.SUPPLY_NAME_ZXHX;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  这里是文件说明
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/03/04
 */
@Service
@Validated
@Slf4j
public class ZXHXProductCategorySyncServiceImpl implements ZXHXProductCategorySyncService {
    @Resource
    private ProductCategoryMapper productCategoryMapper;

    @Override
    public int autoSync() {
        int resultCount = 0;
        List<ZXHXCategoryItemRespDTO> data = ZXHXApiClientFactory.productClient().getAllCategory();
        if (CollUtil.isEmpty(data)) {
            return resultCount;
        }
        List<ProductCategoryDO> categoryExists = productCategoryMapper.selectBySupplyRelatedIds(data.stream().map(ZXHXCategoryItemRespDTO::getId).collect(Collectors.toSet()));
        List<ProductCategoryDO> insertList = new ArrayList<>();
        for (ZXHXCategoryItemRespDTO itemRespDTO : data) {
            if (categoryExists.stream().anyMatch(categoryDO -> itemRespDTO.getId().equals(categoryDO.getSupplyRelatedId()))) {
                continue;
            }
            ProductCategoryDO productCategoryDO = buildProductCategoryDO(itemRespDTO);
            insertList.add(productCategoryDO);
        }
        log.info("插入自营产品分类数据：{} 条", insertList.size());
        productCategoryMapper.insertBatch(insertList);
        resultCount += insertList.size();
        List<ProductCategoryDO> categoryAll = productCategoryMapper.selectListByStatus(SELF_OPERATED_SHOP_ID, null);
        List<ProductCategoryDO> updateList = toProductCategoryDOS(categoryAll);
        log.info("更新自营产品分类父级编号：{} 条", updateList.size());
        productCategoryMapper.updateById(updateList);
        return resultCount;
    }

    @Nonnull
    private List<ProductCategoryDO> toProductCategoryDOS(List<ProductCategoryDO> categoryAll) {
        List<ProductCategoryDO> updateList = new ArrayList<>();
        for (ProductCategoryDO category : categoryAll) {
            if (!SUPPLY_NAME_ZXHX.equals(category.getSupplyName())) {
                continue;
            }
            if (category.getSupplyRelatedParentId() == 0L) {
                ProductCategoryDO productCategoryDO = new ProductCategoryDO();
                productCategoryDO.setId(category.getId());
                productCategoryDO.setParentId(0L);
                updateList.add(productCategoryDO);
                continue;
            }
            for (ProductCategoryDO it : categoryAll) {
                if (Objects.equals(category.getSupplyRelatedParentId(), it.getSupplyRelatedId())) {
                    ProductCategoryDO productCategoryDO = new ProductCategoryDO();
                    productCategoryDO.setId(category.getId());
                    productCategoryDO.setParentId(it.getId());
                    updateList.add(productCategoryDO);
                    break;
                }
            }
        }
        return updateList;
    }

    @Nonnull
    private ProductCategoryDO buildProductCategoryDO(ZXHXCategoryItemRespDTO itemRespDTO) {
        ProductCategoryDO productCategoryDO = new ProductCategoryDO();
        productCategoryDO.setShopId(SELF_OPERATED_SHOP_ID);
        productCategoryDO.setParentId(0L);
        productCategoryDO.setName(itemRespDTO.getName());
        productCategoryDO.setPicUrl("");
        productCategoryDO.setLinkUrl("#");
        productCategoryDO.setSort(itemRespDTO.getId().intValue());
        productCategoryDO.setDepth(itemRespDTO.getLevel() + 1);
        productCategoryDO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        productCategoryDO.setSupplyName(SUPPLY_NAME_ZXHX);
        productCategoryDO.setSupplyRelatedId(itemRespDTO.getId());
        productCategoryDO.setSupplyRelatedParentId(itemRespDTO.getParentId());
        return productCategoryDO;
    }

}
